import "./ZTlogin.css";
import ZTloginimg from '../../assets/ZTlogin.png'
import { PhoneOutlined, CheckCircleOutlined } from '@ant-design/icons';
import { Form, Button, Input, message, FormInstance, Row, Col } from "antd";
import api from '../../api/index'
import { useNavigate } from 'react-router-dom';
import  { useState, useEffect, createRef } from 'react';

interface LoginFormValues {
    phone: string;
    verificationCode: string;
}

function ZTForgetPasswordLogin() {
    const navigate = useNavigate();
    const [countdown, setCountdown] = useState(0);
    const [timer, setTimer] = useState<NodeJS.Timeout | null>(null);
    const form = createRef<FormInstance<LoginFormValues>>();

    const getVerificationCode = async () => {
        const formInstance = form.current;
        if (!formInstance) {
            return;
        }
        const phoneNumber = formInstance.getFieldValue('phone');
        if (!phoneNumber) {
            message.error('请输入手机号码');
            return;
        }
        await api.post('/sendVerificationCode', { phone: phoneNumber });
        message.success('验证码已发送，请查收');
        setCountdown(60);
        const newTimer = setInterval(() => {
            setCountdown(prevCountdown => {
                if (prevCountdown > 0) {
                    return prevCountdown - 1;
                } else {
                    clearInterval(newTimer);
                    setTimer(null);
                    return 0;
                }
            });
        }, 1000);
        setTimer(newTimer);

    };

    const onFinish = async (values: LoginFormValues) => {
        console.log(values);
        
        try {
            const response = await api.post('/loginByPhone', values);
            const { username } = response.data;
            localStorage.setItem('username', username);
            console.log('登录成功');
            // 登录成功后跳转到仪表盘页面
            // navigate('/dashboard');
        } catch (error) {
            if (error instanceof Error) {
                const status = (error as any).response?.status;
                const messageText = (error as any).response?.data?.message || '登录失败，请稍后重试';
                if (status === 401) {
                    message.error('手机号码或验证码错误');
                } else {
                    message.error(messageText);
                }
            } else {
                message.error('未知错误');
            }
        }
    };

    useEffect(() => {
        return () => {
            if (timer) {
                clearInterval(timer);
            }
        };
    }, [timer]);

    return (
        <div className="ZTlogin">
            <div className="ZTloginmain">
                <img src={ZTloginimg} alt="" />
                <div>
                    <h2>门诊医生工作站 - 忘记密码</h2>
                    <p>通过手机号验证登录</p>
                    <div style={{ width: '80%', margin: 'auto' }}>
                        <Form
                            ref={form}
                            name="phone_login"
                            className="login-form"
                            onFinish={onFinish}
                        >
                            <Form.Item
                                name="phone"
                                rules={[{ required: true, message: '手机号码不能为空' }, { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' }]}
                            >
                                <Input
                                    prefix={<PhoneOutlined className="site-form-item-icon" />}
                                    placeholder="请输入手机号码" />
                            </Form.Item>
                            <Form.Item extra="We must make sure that your are a human.">
                                <Row gutter={8}>
                                    <Col span={15}>
                                        <Form.Item
                                            name="verificationCode"
                                            rules={[{ required: true, message: '验证码不能为空' }]}
                                        >
                                            <Input
                                                prefix={<CheckCircleOutlined className="site-form-item-icon" />}
                                                placeholder="请输入验证码" />
                                        </Form.Item>
                                    </Col>
                                    <Col span={9}>
                                        <Button
                                            type="primary"
                                            onClick={() => getVerificationCode()}
                                            disabled={countdown > 0}
                                            className="login-form-button"
                                        >
                                            {countdown > 0 ? `${countdown}s后重试` : '获取验证码'}
                                        </Button>
                                    </Col>
                                </Row>
                            </Form.Item>

                            <Form.Item>
                                <Button 
                                    type="primary" 
                                    htmlType="submit" 
                                    className="login-form-button">
                                    登录
                                </Button>
                            </Form.Item>
                        </Form>
                    </div>

                </div>
            </div>
        </div>
    );
}

export default ZTForgetPasswordLogin;